package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.AppUser;

import com.ruoyi.system.mapper.SyAppUserMapper;
import com.ruoyi.system.service.IAppUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

@Service
public class AppUserServiceImpl implements IAppUserService {
    @Resource
    private SyAppUserMapper appUserMapper;

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectAppUserByUserName(String userName) {
        return appUserMapper.selectAppUserByUserName(userName);
    }


    /**
     * 修改保存用户信息
     *
     * @param appUser 用户信息
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 密码校验
     *
     * @param passwordHash 明文
     * @param salt     盐
     * @param hashPwd  密文
     * @return boolean
     */
    public boolean checkPassword(String passwordHash, String salt, String hashPwd) {
        return hashPwd.equals(DigestUtils.md5DigestAsHex(passwordHash.concat(salt).getBytes()));
    }

    /**
     * 随即生成盐
     * 8位随机数
     *
     * @return salt 盐
     */
    private String generateSalt() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    public static void main(String[] args) {
        AppUserServiceImpl appUserService = new AppUserServiceImpl();
        String password = "123456";
        String salt = appUserService.generateSalt();
        System.out.printf("明文密码：%s%n", password);
        System.out.printf("盐：%s%n", salt);
        System.out.printf("密文密码：%s%n", DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }
}